<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="mytag" uri="/WEB-INF/tag/tag.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<mytag:head title="农产品溯源系统-设置" defineJs="/ncpsy/static/js/isQyLogin.js"
            defineCss="/ncpsy/static/css/tab-style.css"/>
<body>
<style>

    .chain-info-wrapper, .block-list-wrapper, .producer-list-wrapper {
        width: 90%;
        margin: 20px auto;
        padding: 20px;
        border-radius: 2px;
        box-shadow: 0 3px 1px -2px rgba(0,0,0,.2), 0 2px 2px 0 rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12);
    }
    .layui-form .layui-form-label {
        width: 200px;
        text-align: left;
    }
    .layui-form .layui-input-block {
        margin-left: 300px;
    }

    .layui-form .layui-form-item {
        margin-bottom: 0;
    }
    .layui-form .layui-form-item:nth-of-type(2n) {
        background: #f5f5f5;
    }

    .layui-form .layui-input {
        border: none;
        background: transparent;
    }

    .block-list-wrapper .layui-form {
        /* width: 90%; */
    }

    .producer-list {
        padding: 24px 0;
    }

    .producer-list > li {
        display: inline-block;
        margin: 5px;
        /*background: #f5f5f5;*/
        padding: 8px 16px;
        position: relative;
        font-weight: bold;
        color: #bcbcbc;
        border: 1px dashed #bcbcbc;
    }
    .producer-list > li::before {
        content: '';
        width: 4px;
        display: block;
        height: 4px;
        background: #bcbcbc;
        border: 2px solid #bcbcbc;
        border-radius: 50%;
        position: absolute;
        left: 3px;
        top: 12px;
    }
    .producer-list .active {
        background-color: #5fb878;
        color: #ffffff;
        border: 1px dashed #5fb878;
    }
    .producer-list > .active::before {
        background: #ffffff;
        border: 2px solid #ffffff;
    }
</style>
</head>
<!-- chain info -->
<div class="chain-info-wrapper">
    <div>
        <h2>区块链网络状态</h2>
    </div>
    <form class="layui-form" lay-filter="chainInfo">
        <!-- Server Version: -->
        <div class="layui-form-item">
            <label class="layui-form-label">区块链版本：</label>
            <div class="layui-input-block">
                <input type="text" name="server_version" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <!-- Chain ID: -->
        <div class="layui-form-item">
            <label class="layui-form-label">区块链 ID：</label>
            <div class="layui-input-block">
                <input type="text" name="chain_id" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <!-- Head Block Timestamp: -->
        <div class="layui-form-item">
            <label class="layui-form-label">最新出块时间：</label>
            <div class="layui-input-block">
                <input type="text" name="head_block_time" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <!-- Head Block #: -->
        <div class="layui-form-item">
            <label class="layui-form-label">最新区块高度 #：</label>
            <div class="layui-input-block">
                <input type="text" name="head_block_num" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <!-- Head Block Producer: -->
        <div class="layui-form-item">
            <label class="layui-form-label">最新区块的出块节点：</label>
            <div class="layui-input-block">
                <input type="text" name="head_block_producer" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <!-- Last Irreversible Block #: -->
        <div class="layui-form-item">
            <label class="layui-form-label">最新不可更改区块高度 #：</label>
            <div class="layui-input-block">
                <input type="text" name="last_irreversible_block_num" disabled
                       autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>
<div class="producer-list-wrapper">
    <h2>出块节点</h2>
    <ul class="producer-list">
        <li></li>
    </ul>
<%--    <div class="vote-wrapper">

        <button class="layui-btn">节点投票提案</button>
        <br>
        <small style="display: inline-block;margin-top: 5px">注：用于管理当前网络出块节点，<b>仅限管理员开启投票提案</b></small>
    </div>--%>
</div>
<!-- block update -->
<div class="block-list-wrapper">
    <h2>最新出块信息</h2>
    <table id="list" lay-filter="list" lay-data="{id: 'idTest'}"></table>
</div>





<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>


<script>
    getProducerList();
    // 从后台获取节点列表
    function getProducerList() {
        $.ajax({
            type:'get',
            url: 'http://128.1.136.87:8090/',
            success(res) {
                console.log(res)
                renderProducers(eval(res))
            },
            error(err) {
                console.log(err)
            }
        })
    }
    // 渲染节点列表
    function renderProducers(data) {
        const producerList = $('.producer-list');
        producerList.empty();
        for (let i = 0, len = data.length; i < len; i++) {
            const $li = $('<li>'+data[i].owner+'</li>');
            producerList.append($li)
        }
    }

    // 获取节点列表，并根据blockinfo的出块节点修改节点状态
    function getProducerEL(producer) {
        const list = $('.producer-list').find('li');
        for (let i = 0, len = list.length; i < len; i++) {
            if (list[i].innerText === producer) {
                list[i].className = 'active'
            } else {
                list[i].className = ''
            }
        }
    }
    // block item
    let item = {"timestamp":"2020/5/22 下午1:39:17",
        "producer":"four.cartel",
        "confirmed":0,
        "previous":"0584cda925ff13cbc765c9cb0c31aee3d3cc07f5590d7cdf768799c38fb3b052",
        "transaction_mroot":"0000000000000000000000000000000000000000000000000000000000000000",
        "action_mroot":"0eea0176742af40918b93a6f5ec6944f27c4a4644cdab48ae15e7e4d239da832",
        "schedule_version":392,
        "new_producers":null,
        "producer_signature":"SIG_K1_KhUU1E1zmMD9ZETi293WZ8f29J7CNChkBj2WbAnYTtXh4tWyZ625L2sJ8fmZoJH2ruR4xLNVVCRDTDLrTfBrKMi2tmc6hL",
        "transactions":[],
        "transaction_num": 0,
        "id":"0584cdaa3b0d36ed50840d53b456d173c8ba4101b37e09408e663b320876c1e1",
        "block_num":92589482,
        "ref_block_prefix":1393394768,
        "ncpName": "",
        "ncpId": ""
    };

    let blockList = []
    // default chain info
    let testChain = {
        "head_block_num":92589482,
        "fork_db_head_block_num":92589482,
        "chain_id":"e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473",
        "head_block_time":"2020-05-22T05:39:17.500",
        "virtual_block_net_limit":524288000,
        "virtual_block_cpu_limit":500000000,
        "last_irreversible_block_num":92589146,
        "server_version":"b39b6bd3",
        "block_cpu_limit":499990,
        "head_block_producer":"four.cartel",
        "fork_db_head_block_id":"0584cdaa3b0d36ed50840d53b456d173c8ba4101b37e09408e663b320876c1e1",
        "last_irreversible_block_id":"0584cc5aa64c232f9b55684329addfd096e8028643841aaf75fa07e6431030f7",
        "block_net_limit":524288,
        "head_block_id":"0584cdaa3b0d36ed50840d53b456d173c8ba4101b37e09408e663b320876c1e1",
        "server_full_version_string":"v2.0.4-b39b6bd3c74ff47fc53fa80aafa2c1941ba82879",
        "server_version_string":"v2.0.4"
    };
    let tableNcp, form;

    layui.use(['table', 'laypage', 'layer', 'form'], function () {
        var table = layui.table;

        //渲染表格
        tableNcp = table.render({
            elem: '#list',
            id: 'idTest',
            // url: '/ncpsy/handle/product/list/'+qyid,
            // where: ncp,
            data: blockList,
            page: true,
            cols: [[
                {field: 'block_num', title: '区块高度', sort: true, fixed: 'left'},
                {field: 'timestamp', title: '时间戳'},
                {field: 'producer', title: '出块节点'},
                {field: 'ncpName', title: '农产品名称'},
                {field: 'ncpId', title: '农产品批次号'}
            ]]
        });

        form = layui.form;
        // 初次渲染表单
        getChainInfo();
    });

    // 每隔1秒获取一次区块数据和chain info 数据
    setInterval(function () {
        getChainInfo();
        getBlock();
    }, 1000)

    // 每隔7秒获取一次农产品数据
    setInterval(function() {
        getNCPInfo()
    }, 7000)

    // 获取区块信息
    let tempBlockNum;
    function getBlock() {
        if (tempBlockNum == testChain.head_block_num) {
            return;
        }
        $.ajax({
            url:'/ncpsy/handle/get_block/'+testChain.head_block_num,
            type:'post',
            headers: {
                "Content-Type": "application/json;charset=utf-8;"
            },
            success:function (res) {
                tempBlockNum = testChain.head_block_num;
                res.transaction_num = res.transactions.length;
                res.timestamp = utc2beijing(res.timestamp);
                updateBlock(res);
                // console.log(res)
            },
            error(err) {
                console.log(err)
            }
        });
    }
    // 更新区块信息
    function updateBlock(data) {
        blockList.unshift(data);
        // if (blockList.length > 6) {
        //     blockList.pop()
        // }
        tableNcp.reload({
            id: 'idTest',
            data: blockList
        });
    }

    // 获取chain info
    function getChainInfo() {
        $.ajax({
            url:'/ncpsy/handle/get_info',
            type:'get',
            headers: {
                "Content-Type": "application/json;charset=utf-8;"
            },
            success:function (res) {
                res.head_block_time = utc2beijing(res.head_block_time);
                testChain = res;
                updateForm(testChain);
                getProducerEL(res.head_block_producer)
            },
            error(err) {
                console.log(err)
            }
        });
    }

    // 获取农产品上链信息
    function getNCPInfo() {
        $.ajax({
            url:'/ncpsy/handle/getNcpInfo',
            type:'get',
            headers: {
                "Content-Type": "application/json;charset=utf-8;"
            },
            success:function (res) {
                if (res) {
                    blockList[0].ncpId = res.ncpid
                    blockList[0].ncpName = res.ncpmc
                }

            },
            error(err) {
                console.log(err)
            }
        });
    }
    // 重新渲染chain info
    function updateForm (data) {
        form.val("chainInfo", data);
    }

    // 将UTC时间转换成北京时间
    function utc2beijing(utc_datetime) {
        // 处理成为时间戳
        timestamp = new Date(Date.parse(utc_datetime));
        timestamp = timestamp.getTime();
        timestamp = timestamp/1000;

        // 增加8个小时，北京时间比utc时间多八个时区
        var timestamp = timestamp+8*60*60;

        // 时间戳转为时间
        var beijing_datetime = new Date(parseInt(timestamp) * 1000).toLocaleString();
        return beijing_datetime; // 2017-03-31 16:02:06
    }

</script>
</body>
</html>